package sgg.algorithm.datastructure.stack;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * @author: Michael
 * @date: 2025/4/28
 * @desc: 逆波兰表达式（后缀表达式） Demo
 */
public class ReversePolishNotationDemo {

    public static void main(String[] args) {
        // 先定义 逆波兰表达式
        // （3+4） & 5 - 6 => 3 4+ 5 * 6 -
        String suffixExpression = "3 4 + 5 * 6 -";

        List<String> list = getListString(suffixExpression);
        System.out.println("rpnList : " + list);

        int res = calculate(list);

        System.out.println("res : " + res);
    }

    public static List<String> getListString(String suffixExpression) {
        String[] split = suffixExpression.split(" ");
        return Arrays.stream(split).toList();
    }

    public static int calculate(List<String> ls) {
        Stack<String> stack = new Stack<>();
        for (String item : ls) {
            if (item.matches("\\d+")){
                // 如果是多位数
                stack.push(item);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                switch (item) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2;
                        break;
                    case "*":
                        res = num1 * num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("运算符有误");
                }
                stack.push(String.valueOf(res));
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
